<script setup>
import {ref, onMounted} from 'vue'

const peerConnection = ref(null)
const dataChannel = ref(null)
const localSdp = ref('')
const remoteSdp = ref('')
const connectionStatus = ref('未连接')
const message = ref('')
const messages = ref([])

// 初始化PeerConnection
const initPeerConnection = () => {
	peerConnection.value = new RTCPeerConnection()

	// ICE候选处理
	peerConnection.value.onicecandidate = (e) => {
		if (e.candidate) {
			console.log("ICE Candidate:", e.candidate);
			localSdp.value = JSON.stringify(peerConnection.value.localDescription)
		}
	}

	// 数据通道处理（接收方）
	peerConnection.value.ondatachannel = (e) => {
		dataChannel.value = e.channel
		setupDataChannel()
	}
}

// 配置数据通道事件
const setupDataChannel = () => {
	dataChannel.value.onmessage = (e) => {
		messages.value.push(`对方：${e.data}`)
	}
	dataChannel.value.onopen = () => {
		connectionStatus.value = '已连接'
	}
}

// 生成SDP Offer
const generateSdp = async () => {
	try {
		dataChannel.value = peerConnection.value.createDataChannel('chatChannel')
		setupDataChannel()

		const offer = await peerConnection.value.createOffer()
		await peerConnection.value.setLocalDescription(offer)
		localSdp.value = JSON.stringify(offer)
		connectionStatus.value = '等待远程连接'
	} catch (e) {
		console.error('生成SDP失败:', e)
	}
}

// 处理远程SDP
const processRemoteSdp = async () => {
	console.log("Local SDP:", localSdp.value);
	console.log("Remote SDP:", remoteSdp.value);
	try {
		const desc = JSON.parse(remoteSdp.value)
		await peerConnection.value.setRemoteDescription(desc)

		console.log(desc.type)
		if (desc.type === 'offer') {
			const answer = await peerConnection.value.createAnswer()
			await peerConnection.value.setLocalDescription(answer)
			localSdp.value = JSON.stringify(answer)
		}

		connectionStatus.value = '远程SDP已处理'
	} catch (e) {
		console.error('处理远程SDP失败:', e)
	}
}

// 发送消息
const sendMessage = () => {
	if (message.value && dataChannel.value?.readyState === 'open') {
		dataChannel.value.send(message.value)
		messages.value.push(`自己：${message.value}`)
		message.value = ''
	}
}

onMounted(() => {
	initPeerConnection()
})
</script>

<template>
	<div class="container">
		<h3>WebRTC连接演示</h3>
		<p>状态：{{ connectionStatus }}</p>

		<div>
			<button @click="generateSdp">生成SDP</button>
			<textarea v-model="localSdp" placeholder="本地SDP信息" rows="5"></textarea>
		</div>

		<div>
			<input v-model="remoteSdp" placeholder="粘贴远程SDP信息" type="text">
			<button @click="processRemoteSdp">处理远程SDP</button>
		</div>

		<div>
			<input v-model="message" @keyup.enter="sendMessage" placeholder="输入消息">
			<button @click="sendMessage">发送</button>
		</div>

		<div class="messages">
			<div v-for="(msg, index) in messages" :key="index">{{ msg }}</div>
		</div>
	</div>
</template>

<style>
.container {
	max-width: 600px;
	margin: 20px auto;
	padding: 20px;
}

textarea {
	width: 100%;
	margin: 10px 0;
}

.messages {
	margin-top: 20px;
	border-top: 1px solid #ccc;
	padding-top: 10px;
}
</style>